package com.xiannimei.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class CSVWriter {
	private ByteArrayOutputStream os = new ByteArrayOutputStream();

    private PrintWriter pw;

    private char separator;

    private char quotechar;
    
    private String lineEnd;

    /** The character used for escaping quotes. */
    public static final char ESCAPE_CHARACTER = '"';

    /** The default separator to use if none is supplied to the constructor. */
    public static final char DEFAULT_SEPARATOR = ',';

    /**
     * The default quote character to use if none is supplied to the
     * constructor.
     */
    public static final char DEFAULT_QUOTE_CHARACTER = '"';
    
    /** The quote constant to use when you wish to suppress all quoting. */
    public static final char NO_QUOTE_CHARACTER = '\u0000';
    
    /** Default line terminator uses platform encoding. */
    public static final String DEFAULT_LINE_END = "\n";
    
    /**
     * Constructs CSVWriter using a comma for the separator.
     *
     */
    public CSVWriter() {
        this(DEFAULT_SEPARATOR);
    }

    /**
     * Constructs CSVWriter with supplied separator.
     * @param separator
     *            the delimiter to use for separating entries.
     */
    public CSVWriter(char separator) {
        this(separator, DEFAULT_QUOTE_CHARACTER);
    }

    /**
     * Constructs CSVWriter with supplied separator and quote char.
     *
     * @param separator
     *            the delimiter to use for separating entries
     * @param quotechar
     *            the character to use for quoted elements
     */
    public CSVWriter(char separator, char quotechar) {
    	this(separator, quotechar, "\n");
    }

    /**
     * Constructs CSVWriter with supplied separator and quote char.
     * @param separator
     *            the delimiter to use for separating entries
     * @param quotechar
     *            the character to use for quoted elements
     * @param lineEnd
     * 			  the line feed terminator to use
     */
    public CSVWriter(char separator, char quotechar, String lineEnd) {
        this.pw = new PrintWriter(os);
        this.separator = separator;
        this.quotechar = quotechar;
        this.lineEnd = lineEnd;
    }
    
    public CSVWriter(String encoding){
    	try {
			this.pw = new PrintWriter(new OutputStreamWriter(os,encoding));
		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException("wrong encoding.");
		}
        this.separator = DEFAULT_SEPARATOR;
        this.quotechar = DEFAULT_QUOTE_CHARACTER;
        this.lineEnd = "\n";
    }
    
    /**
     * Writes the entire list to a CSV file. The list is assumed to be a
     * String[]
     *
     * @param allLines
     *            a List of String[], with each String[] representing a line of
     *            the file.
     */
    public byte[] writeAll(List<String[]> allLines)  {
    	if(allLines != null){
    		for(String[] nextLine : allLines)
    			writeNext(nextLine);
    	}        
    	pw.flush();
        pw.close();
        try {
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("Generate CSV File Error");
		}
    	return os.toByteArray();
    }    
    
    /**
     * Writes the next line to the file.
     *
     * @param nextLine
     *            a string array with each comma-separated element as a separate
     *            entry.
     */
    public void writeNext(String[] nextLine) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < nextLine.length; i++) {

            if (i != 0) {
                sb.append(separator);
            }

            String nextElement = nextLine[i];
            if (nextElement == null)
                continue;
            if (quotechar !=  NO_QUOTE_CHARACTER)
            	sb.append(quotechar);
            for (int j = 0; j < nextElement.length(); j++) {
                char nextChar = nextElement.charAt(j);
                if (nextChar == quotechar) {
                    sb.append(ESCAPE_CHARACTER).append(nextChar);
                } else if (nextChar == ESCAPE_CHARACTER) {
                    sb.append(ESCAPE_CHARACTER).append(nextChar);
                } else {
                    sb.append(nextChar);
                }
            }
            if (quotechar != NO_QUOTE_CHARACTER)
            	sb.append(quotechar);
        }
        
        sb.append(lineEnd);
        pw.write(sb.toString());

    }

}
